// pages/competition/competition.js
var app = getApp();
var config = require('../../../config.js');
var socketOpen = false;
var socketTask;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    openId: app.globalData.openid,
    isShow: false,
    id: ''
  },

  // 跳转好友对战
  friendBattle: function (e) {
    wx.redirectTo({
      url: '../invitefriend/invitefriend',
    })

  },




  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    wx.request({
      url: config.getCompetitionType,
      data: {
        type: 2
      },
      method: 'POST',
      success: function (res) {
        if (res.data.success == 0) {
          console.log(res.data)
          that.setData({
            typeList: res.data.rows
          });
        }
      },

      fail: function (error) {
        console.log(error)
      }
    })
  },


  /**
    * 获取当前点击题库的id
    */
  onTypeTap: function (e) {
    var id = e.currentTarget.dataset.typeid;
    console.log('2'+id)
    this.setData({
      id: id
    });
    try {
      wx.setStorageSync(config.quesTypeId, id)
    } catch (e) {
    }

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
      this.setData({
        isShow: true,
      });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },



  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var that = this;
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '我在XX（擂台赛名称）挑战，没有对手，欢迎来战！',
      path: '/pages/index/index?pageId=' + config.competition,
      success: function (res) {
        that.friendBattle();
      }
    }
  },


  /**
   * 好友对战
   */
  toConnect: function (e) {
    var that = this;
    //判断是否选择题库
    var id = this.data.id;
    console.log("当前题库分类id= "+id)
    if (id == '' || id == null || id== -1) {
      wx.showToast({
        icon: 'none',
        title: '请返回选择题目类型',
      })
      return;
    }

    //=============web socket 连接================================
    socketTask = app.globalData.mSocketTask;
    if (app.globalData.socketOpen){
      var msg = {
        openId: app.globalData.openid,
        type: 1,
        questionBankId: id
      }
      if (typeof (msg) === 'object') {
        msg = JSON.stringify(msg);
      }
      socketTask.send({
        data: msg,
        success:function(res){
          console.log("发送题库分类id成功"+msg);
        }
      });

    }else {
      app.connectSocket();
      socketTask = app.globalData.mSocketTask;
      socketTask.onOpen(function (res) {
        console.log('WebSocket连接已打开！')
        app.globalData.socketOpen = true
        var msg = {
          openId: app.globalData.openid,
          type: 1,
          questionBankId: id
        }
        if (typeof (msg) === 'object') {
          msg = JSON.stringify(msg);
        }
        socketTask.send({
          data: msg,
           success: function (res) {
            console.log("发送题库分类id成功" + msg);
          }
        });

      });
    }


    socketTask.onError(function (res) {
      console.log('WebSocket连接打开失败，请检查！')
    })
    socketTask.onClose(function (res) {
      app.globalData.socketOpen = false
      console.log('WebSocket 已关闭！')
      if(that.data.isShow){
        wx.navigateBack({
          delta: -1
        })
      }
     
    });
    socketTask.onMessage(function (res) {
      // console.log('Competition 收到服务器内容：' + res.data)
      var response = JSON.parse(res.data);
      //如果服务器创建房间成功 跳转到另一个界面  继续等待
      if (response.success == 0) {
        if (response.type == 1) {
          try {
            wx.setStorageSync(config.roomId, response.data)
          } catch (e) {
          }
          that.friendBattle();
        }
      }

    });

  },


  netizenBattle: function(){

    wx.showToast({
      icon: 'none',
      title: '功能开发中...',
    })

  },

    /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //退出时 结束socket链接

    // if (socketTask && app.globalData.socketOpen) {
    //   socketTask.close({
    //     success: function (res) {
    //       console.log("socket连接关闭成功");
    //     }

    //   });
    // }
    console.log("Competition onUnload");
    this.setData({
      isShow: false,
    });
  },



})